package com.shigen.demo.ForkJoinDemo;

import cn.hutool.core.date.StopWatch;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import lombok.SneakyThrows;

/**
 * @author shigenfu
 * @date 2024/4/8 17:05
 */
public class SumRecursive {

    public static class RecursiveSumTask implements Callable<Long> {

        // 拆分粒度
        public static final int THRESHOLD = 10_0000;
        int low;
        int high;
        int[] arr;
        ExecutorService executorService;

        RecursiveSumTask(ExecutorService executorService, int[] arr, int low, int high) {
            this.executorService = executorService;
            this.arr = arr;
            this.low = low;
            this.high = high;
        }

        @Override
        public Long call() throws Exception {
            long result = 0;
            if (high - low < THRESHOLD) {
                for (int i = low; i < high; i++) {
                    result += arr[i];
                }
            } else {
                int mid = (low + high) / 2;
                RecursiveSumTask leftTask = new RecursiveSumTask(executorService, arr, low, mid);
                RecursiveSumTask rightTask = new RecursiveSumTask(executorService, arr, mid, high);
                Future<Long> lr = executorService.submit(leftTask);
                Future<Long> rr = executorService.submit(rightTask);
                result = lr.get() + rr.get();
            }
            return result;
        }
    }

    @SneakyThrows
    public static void main(String[] args) {
        int[] arr = new int[10000_0000];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i + 1;
        }

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        ExecutorService executorService = Executors.newCachedThreadPool();
        RecursiveSumTask recursiveSumTask = new RecursiveSumTask(executorService, arr, 0, arr.length);
        Long result = executorService.submit(recursiveSumTask).get();
        executorService.shutdown();
        stopWatch.stop();
        System.out.println("Sum of 1 to 100000 is: " + result);
        System.out.println("代码执行时间：" + stopWatch.getLastTaskTimeMillis() + "毫秒");

    }

}
